package com.team06.dao;

import com.team06.pojo.Dfue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class DfueDao {
    private static final Logger LOGGER = LoggerFactory.getLogger(DfueDao.class.getName());
    private final JdbcTemplate jdbcTemplate;

    public DfueDao(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public void insertMessage(Dfue entity) {
        // 先检查是否已存在该航班
        String checkSql = "SELECT COUNT(*) FROM MSG_DFME_DFUE WHERE DFLT_FLID = ?";
        int count = jdbcTemplate.queryForObject(checkSql, Integer.class, entity.getDfltFLID());

        if (count > 0) {
            LOGGER.info("航班数据已存在，跳过插入: " + entity.getDfltFLID());
            return;
        }

        String sql = "INSERT INTO MSG_DFME_DFUE (" +
                "META_SNDR, META_RCVR, META_SEQN, META_DDTM, META_TYPE, META_STYP, " +
                "DFLT_FLID, DFLT_AFID, DFLT_FFID, DFLT_FIDE, DFLT_AWCD, DFLT_FLNO, " +
                "DFLT_FEXD, DFLT_FIMD, DFLT_FLIO, DFLT_FLTK, DFLT_FATT, DFLT_PATT, " +
                "DFLT_MFID, DFLT_MFFI, DFLT_CFTP, DFLT_CFNO, DFLT_STAT, DFLT_ABST, " +
                "DFLT_ABRS, DFLT_ISTA, DFLT_IAST, DFLT_IARS, DFLT_MSTA, DFLT_MABS, " +
                "DFLT_MABR, DFLT_MIST, DFLT_MIAS, DFLT_MIAR, DFLT_BORT, DFLT_MBOR, " +
                "DFLT_TBRT, DFLT_MTBR, DFLT_LBDT, DFLT_MLBD, DFLT_POKT, DFLT_MPOK, " +
                "DFLT_APOT, DFLT_DETT, DFLT_DRTT, DFLT_DELT, DFLT_DRLT, DFLT_VIP, " +
                "DFLT_PAST, DFLT_CONT, DFLT_PROX, DFLT_TMCD_NMCD, DFLT_TMCD_JMCD, DFLT_SFLG) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " +
                "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " +
                "?, ?, ?, ?, ?, ?, ?,?,?,?,?)";

        try {
            jdbcTemplate.update(sql,
                    entity.getMetaSnDR(),
                    entity.getMetaRCVR(),
                    entity.getMetaSEQN(),
                    entity.getMetaDDTM(),
                    entity.getMetaTYPE(),
                    entity.getMetaSTYP(),
                    entity.getDfltFLID(),
                    entity.getDfltAFID(),
                    entity.getDfltFFID(),
                    entity.getDfltFIDE(),
                    entity.getDfltAWCD(),
                    entity.getDfltFLNO(),
                    entity.getDfltFEXD(),
                    entity.getDfltFIMD(),
                    entity.getDfltFLIO(),
                    entity.getDfltFLTK(),
                    entity.getDfltFATT(),
                    entity.getDfltPATT(),
                    entity.getDfltMFID(),
                    entity.getDfltMFFI(),
                    entity.getDfltCFTP(),
                    entity.getDfltCFNO(),
                    entity.getDfltSTAT(),
                    entity.getDfltABST(),
                    entity.getDfltABRS(),
                    entity.getDfltISTA(),
                    entity.getDfltIAST(),
                    entity.getDfltIARS(),
                    entity.getDfltMSTA(),
                    entity.getDfltMABS(),
                    entity.getDfltMABR(),
                    entity.getDfltMIST(),
                    entity.getDfltMIAS(),
                    entity.getDfltMIAR(),
                    entity.getDfltBORT(),
                    entity.getDfltMBOR(),
                    entity.getDfltTBRT(),
                    entity.getDfltMTBR(),
                    entity.getDfltLBDT(),
                    entity.getDfltMLBD(),
                    entity.getDfltPOKT(),
                    entity.getDfltMPOK(),
                    entity.getDfltAPOT(),
                    entity.getDfltDETT(),
                    entity.getDfltDRTT(),
                    entity.getDfltDELT(),
                    entity.getDfltDRLT(),
                    entity.getDfltVIP(),
                    entity.getDfltPAST(),
                    entity.getDfltCONT(),
                    entity.getDfltPROX(),
                    entity.getDfltTmcdNmcd(),
                    entity.getDfltTmcdJmcd(),
                    "" // DFLT_SFLG设置为空字符串
            );
            LOGGER.info("数据插入成功（通过 Spring JDBC）");

            // 插入关联表数据
            insertFlightSegments(entity.getFlightSegments(), entity.getDfltFLID());
            insertGtlsGate(entity.getGtlsGate(), entity.getDfltFLID());
            insertStlsStnd(entity.getStlsStnd(), entity.getDfltFLID());

        } catch (Exception e) {
            LOGGER.error("Failed to insert message into database", e);
            throw new RuntimeException("Failed to insert message into database", e);
        }
    }

    private void insertFlightSegments(List<Dfue.FlightSegment> segments, String dfltFLID) {
        if (segments != null && !segments.isEmpty()) {
            String sql = "INSERT INTO ARPT (FLIGHT_ID, SEGMENT_TYPE, APNO, APCD, FPTT, FETT, FRTT, FPLT, FELT, FRLT, APAT) " +
                    "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

            for (Dfue.FlightSegment segment : segments) {
                jdbcTemplate.update(sql,
                        dfltFLID,
                        segment.getSegmentType(),
                        segment.getApno(),
                        segment.getApcod(),
                        segment.getFptt(),
                        segment.getFett(),
                        segment.getFrtt(),
                        segment.getFplt(),
                        segment.getFelt(),
                        segment.getFrlt(),
                        segment.getApat()
                );
            }
        }
    }

    private void insertGtlsGate(Dfue.GtlsGate gtlsGate, String dfltFLID) {
        if (gtlsGate != null) {
            // 修改 SQL 语句，使用 FLIGHT_ID 关联航班
            String sql = "INSERT INTO DFME_GTLS_GATE (FLIGHT_ID, GTNO, GATE_ID, CODE, GTAT, ESTR, EEND, RSTR, REND, BTSC) " +
                    "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            jdbcTemplate.update(sql,
                    dfltFLID,
                    gtlsGate.getGtno(),
                    gtlsGate.getId(),
                    gtlsGate.getCode(),
                    gtlsGate.getGtat(),
                    gtlsGate.getEstr(),
                    gtlsGate.getEend(),
                    gtlsGate.getRstr(),
                    gtlsGate.getRend(),
                    gtlsGate.getBtsc()
            );
        }
    }

    private void insertStlsStnd(Dfue.StlsStnd stlsStnd, String dfltFLID) {
        if (stlsStnd != null) {
            // 修改 SQL 语句，使用 FLIGHT_ID 关联航班
            String sql = "INSERT INTO DFME_STLS_STND (FLIGHT_ID, STNO, CODE, ESTR, EEND, RSTR, REND, CSSI, BTSC) " +
                    "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
            jdbcTemplate.update(sql,
                    dfltFLID,
                    stlsStnd.getStno(),
                    stlsStnd.getCode(),
                    stlsStnd.getEstr(),
                    stlsStnd.getEend(),
                    stlsStnd.getRstr(),
                    stlsStnd.getRend(),
                    stlsStnd.getCssi(),
                    stlsStnd.getBtsc()
            );
        }
    }


    private void insertTmcd(String nmcd, String jmcd, String dfltFLID) {
        String sql = "UPDATE MSG_DFME_DFUE SET DFLT_TMCD_NMCD = ?, DFLT_TMCD_JMCD = ? WHERE DFLT_FLID = ?";
        jdbcTemplate.update(sql, nmcd, jmcd, dfltFLID);
    }
}